﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace WEI_Share.Helpers
{
	public sealed class Utilities
	{
		#region Constructor
        /// <summary>
        /// Private constructor
        /// </summary>
		private Utilities()
        {
        }
        #endregion


        public static bool WinsatExecutableExited { get; set; }


		/// <summary>
		/// Determines if the current version of windows is valid (Vista, 7, Server 2008)
		/// </summary>
		/// <returns></returns>
		public static bool IsValidWindowsVersion()
		{
			System.OperatingSystem osInfo = System.Environment.OSVersion;
			//6 - Vista, 7, Server 2008
			if (osInfo.Version.Major == 6)
			{
                //windows 7 = 1
                if(osInfo.Version.Minor == 1)
				    return true;
			}

			return false;
		}

		/// <summary>
		/// Launches the winsat program
		/// </summary>
        public static bool RunWinSatProgram()
        {
			bool isLaunched = false;

            WinsatExecutableExited = false;

            System.Diagnostics.Process winSatProcess = new System.Diagnostics.Process();
            winSatProcess.StartInfo.FileName = Helpers.Globals.WinSatExecutable;
            winSatProcess.StartInfo.Arguments = Helpers.Globals.WinSatExecutableParameters;


            winSatProcess.EnableRaisingEvents = true;

			winSatProcess.Exited += new EventHandler(WinSatProcess_Exited);

			try
			{
				winSatProcess.Start();
				isLaunched = true;
			}
			catch
			{
				//System.Windows.MessageBox.Show("Error launching Windows Site Assessment application.");
			}

			return isLaunched;
        }


        /// <summary>
		/// Handle Exited event.  Sets member which is checked by progress window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void WinSatProcess_Exited(object sender, System.EventArgs e)
        {
            WinsatExecutableExited = true;
        }


		/// <summary>
		/// Checks the status of the file and fills in the messages accordingly
		/// </summary>
		public static System.IO.FileInfo GetLatestWinSATFileInfo()
		{
			// Check if the computer has a \WinSAT dir.
			if (System.IO.Directory.Exists(Helpers.Globals.WinSatDataStoreFolderPath))
			{
				// Because the program makes a new XML file on every update of the score,
				// we need to calculate the most recent, just incase the owner has upgraded.

				System.IO.DirectoryInfo xmlFolder = new System.IO.DirectoryInfo(Helpers.Globals.WinSatDataStoreFolderPath);
				DateTime lastAccessTime = DateTime.MinValue;

				return xmlFolder.GetFiles("*.WinSAT.xml").ToList().OrderByDescending(i => i.Name).FirstOrDefault();
			}

			return null;
		}


		/// <summary>
		/// Retrieves the date from the beginning of the WinSat filename and creates a datetime object from it
		/// </summary>
		/// <param name="fileName"></param>
		/// <returns>The converted datetime or null</returns>
		public static DateTime? GetDateFromFileName(string fileName)
		{
			//VISTA:  2009-06-23 17.13.21.155 Assessment (Formal).WinSAT.xml
			//int position = fileName.IndexOf("Assessment");
			//Win7:  2009-06-23 17.13.21.155 Formal.Assessment (Recent).WinSAT.xml
			int position = fileName.IndexOf("Formal.Assessment");
			if (position > -1)
			{
				if (fileName.Length >= (position - 1))
				{
					string dateTimeText = fileName.Substring(0, position - 1);
					position = dateTimeText.LastIndexOf('.');
					if (position > -1)
					{
						return Convert.ToDateTime(dateTimeText.Substring(0, position - 1).Replace(".", ":") + dateTimeText.Substring(position));
					}
				}
			}

			return null;
		}

		/// <summary>
		/// Loads the xml into the Winsat XML member
		/// </summary>
		/// <param name="fileName"></param>
		public static void LoadXmlData(string fileName)
		{
			if (!string.IsNullOrEmpty(fileName))
			{
				XmlTextReader reader = new XmlTextReader(fileName);
				reader.WhitespaceHandling = WhitespaceHandling.None;

				XElement doc = XElement.Load(reader);

				Helpers.Globals.WinSatXmlDocument = doc;

				reader.Close();
			}
			else
				Helpers.Globals.WinSatXmlDocument = null;
		}

		/// <summary>
		/// Used to retrieve the value of the first instance of a specific element in the list
		/// </summary>
		/// <param name="itemList"></param>
		/// <param name="itemName"></param>
		/// <returns>the value of the element or the empty string</returns>
		public static string GetElementValue(List<XElement> itemList, string itemName)
		{
			var specific = itemList.Where(i => i.Name == itemName).FirstOrDefault();

			if (specific != null)
				return specific.Value;

			return string.Empty;
		}

		/// <summary>
		/// Used to retrieve the value of a specific attribute from the first instance of a specific element in the list
		/// </summary>
		/// <param name="itemList"></param>
		/// <param name="itemName">the name of the element to look for</param>
		/// <param name="attributeName">the name of the attribute to look for</param>
		/// <returns>the attribute value or the empty string</returns>
		public static string GetElementAttributeValue(List<XElement> itemList, string itemName, string attributeName)
		{
			var specific = itemList.Where(i => i.Name == itemName).FirstOrDefault();

			if (specific != null)
				if(specific.HasAttributes)
					return specific.Attribute(attributeName).Value;

			return string.Empty;
		}

		/// <summary>
		/// Used to retrieve the value of a specific attribute from the element
		/// </summary>
		/// <param name="item"></param>
		/// <param name="attributeName">the atrribute to look for</param>
		/// <returns>the attribute value or the empty string</returns>
		public static string GetElementAttributeValue(XElement item, string attributeName)
		{
			if (item.HasAttributes)
				return item.Attribute(attributeName).Value;

			return string.Empty;
		}
	}
}
